package com.google.code.pathlet.eshop.party.service.impl;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.transaction.annotation.Transactional;

import com.google.code.pathlet.config.anno.InstanceIn;
import com.google.code.pathlet.eshop.party.service.UserService;
import com.google.code.pathlet.eshop.party.vo.UserVo;
import com.google.code.pathlet.eshop.party.vo.UserQueryVo;
import com.google.code.pathlet.jdbc.EntityInsertDef;
import com.google.code.pathlet.jdbc.EntityRowMapper;
import com.google.code.pathlet.jdbc.EntityUpdateDef;
import com.google.code.pathlet.jdbc.ExtJdbcTemplate;
import com.google.code.pathlet.util.ValueUtils;
import com.google.code.pathlet.vo.QueryResultVo;


public class UserServiceImpl implements UserService {

	private ExtJdbcTemplate jdbcTemplate = null;

	@InstanceIn(path="/dataSource.pb")  
	private DataSource dataSource;

	public ExtJdbcTemplate getJdbcTemplate()  {
		if(this.jdbcTemplate == null) {
			this.jdbcTemplate = new ExtJdbcTemplate(dataSource);
			this.jdbcTemplate.registerInsertEntity(new EntityInsertDef("T_USER", UserVo.class, "T_USER"));
			this.jdbcTemplate.registerUpdateEntity(new EntityUpdateDef("T_USER", UserVo.class, "T_USER", new String[] {"username"}));
		}
		return this.jdbcTemplate;
	}
		
	public void deleteUsers(String[] usernames) {
		for(String username : usernames) {
			getJdbcTemplate().update("DELETE from T_USER where USERNAME= ? ", new Object[] { username });
		}
	}
	
	@Transactional(readOnly=true)
	public UserVo getUser(String username, String password) {
		return (UserVo)getJdbcTemplate().queryForObject(
				"select t.* from T_USER t where USERNAME=? and PASSWORD=?", 
				new Object[]{username, password}, new EntityRowMapper<UserVo>(UserVo.class));
	}

	@Transactional(readOnly=true)
	public UserVo getUser(String username) {
		UserVo user = (UserVo)getJdbcTemplate().queryForObject(
				"select t.* from T_USER t where USERNAME=?",
				new Object[]{username}, new EntityRowMapper<UserVo>(UserVo.class));
		return user;

	}
	
	
	@Transactional(readOnly=true)
	public QueryResultVo<UserVo> queryUserList(UserQueryVo parameters) {
		StringBuffer sqlBuff = new StringBuffer(" from T_USER u where 1=1 ");

		if(ValueUtils.notEmpty(parameters.getUsername())) {
			sqlBuff.append(" and u.username like '%" + ValueUtils.escapeSQLParam(parameters.getUsername()) + "%'");
		}
		
		if(ValueUtils.notEmpty(parameters.getEmail())) {
			sqlBuff.append(" and u.email = '" + ValueUtils.escapeSQLParam(parameters.getEmail()) + "'");
		}
		
		StringBuilder countSql = new StringBuilder();
		countSql.append("select count(u.username)").append(sqlBuff);
		
		StringBuilder listSql = new StringBuilder();
		listSql.append("select u.*").append(sqlBuff);
		
		//order by clause
		if("username".equals(parameters.getSortName())) {
			listSql.append(" order by u.username ").append(parameters.getSortOrder());
		}
		
		//Get total records count
		Long rowCount = getJdbcTemplate().queryForLong(countSql.toString());
		
		//Get rows data
		List<UserVo> listResult = getJdbcTemplate()
				.query(parameters.getStartIndex(), parameters.getFetchSize(), listSql.toString(), null, new EntityRowMapper<UserVo>(UserVo.class, null));
		
		return new QueryResultVo<UserVo>(rowCount, listResult);
	}

	public void saveUser(UserVo user) {
		getJdbcTemplate().insertEntity("T_USER", user);
	}
	
	public void updateUser(UserVo user) {
		getJdbcTemplate().updateEntity("T_USER", user);
	}


	public String getVersion() {
		Method method = null;
		try {
			method = UserVo.class.getMethod("getPhone");
		} 
		catch (NoSuchMethodException nsme) {
			method = null;
		}
		catch (SecurityException se) {
			method = null;
		}
		
		if(method != null) {
			return "2";
		}
		else {
			return "1";
		}
	}

	

}
